package v1

import (
	"errors"
	"gin-study/app/http/requests"
	"gin-study/app/http/responses"
	"gin-study/app/services"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"gorm.io/gorm"
)

var User = new(user)

type user struct {
	controller
}

func (this *user) Index(c *gin.Context) interface{} {
	var req *requests.UserListReq
	err := c.Bind(&req)
	if err != nil {
		return responses.BadRequest(err.Error(), nil)
	}
	users := services.User.GetUsers(req.Keywords, this.GetPage(c))
	return responses.Ok("ok", gin.H{
		"users": users,
	})
}

func (this *user) Get(c *gin.Context) interface{} {
	id := cast.ToUint(c.Param("id"))

	user, err := services.User.GetUserById(id)
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		return responses.NotFind("找不到这个会员", nil)
	}
	if err != nil {
		return responses.ServerError(err.Error(), nil)
	}
	return responses.Ok("ok", gin.H{
		"user": user,
	})
}

func (this *user) Post(c *gin.Context) interface{} {
	var req *requests.UserCreateReq
	err := c.Bind(&req)
	if err != nil {
		return responses.BadRequest(err.Error(), nil)
	}
	user, err := services.User.CreateUser(req)
	if err != nil {
		return responses.ServerError(err.Error(), nil)
	}
	return responses.Ok("ok", gin.H{
		"user": user,
	})
}

func (this *user) Put(c *gin.Context) interface{} {
	id := cast.ToUint(c.Param("id"))
	var req *requests.UserUpdateReq
	err := c.Bind(&req)
	if err != nil {
		return responses.BadRequest(err.Error(), nil)
	}
	user, err := services.User.UpdateUser(id, req)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return responses.NotFind("找不到这个会员", nil)
	}
	if err != nil {
		return responses.ServerError(err.Error(), nil)
	}
	return responses.Ok("ok", gin.H{
		"user": user,
		"id":   id,
	})
}

func (this *user) Delete(c *gin.Context) interface{} {
	id := c.Param("id")
	services.User.DeleteUser(id)
	return responses.Ok("ok", nil)
}
